import Row from "./Row";
import ColGroup from "./ColGroup";
import { useForm } from "../../../framework/common/context/metadata-context";
import clsx from "clsx";
import { forwardRef } from "react";
import useTableReady from "./useTableReady";
import { fieldFilter, fieldFilterNormal } from "../../../framework/common/utils/filter";
import set from "lodash/set";
import get from "lodash/get";
import { InjectProvider } from "../../../framework/common/context/inject-context";
import { useSubscribe } from "../../../framework/common/eventBus";
import { useUpdate } from "ahooks";

export default function ({ data = [], group, isSetFixedColumnPc = false }) {
  const form = useForm();

  let fields = group.fields.filter(fieldFilter) || [];
  let showTotalFields = fields.filter((f) => f.designProps?.isTotal === true && f.isHidden!==true) || [];
  //如果没有合计列，或者没有数据，或者是编辑表格就不显示summary
  if (showTotalFields.length === 0 || data.length === 0) {
    return null;
  }
  let totalData = {};
  //计算合计列的合计值
  showTotalFields.forEach((s) => {
    s.preFixStr = "合计：";
    let fieldCode = s.code;
    let total = 0;
    data.forEach((d) => {
      total += Number(d[fieldCode]) || 0;
    });
    totalData[fieldCode] = total;
  });

  let dataPrefix = "form.form_data.childrenSummary.";

  //把合计列计算好的信息放入form_data.childrenSummary暂存
  set(form.data, dataPrefix + group.code, [totalData]);

  let normalFilterFields = group.fields.filter(fieldFilterNormal);
  let theTable = (
    <tfoot>
      <InjectProvider value={{ prefixStr: "合计：" }}>
        {get(form.data, dataPrefix + group.code, []).map((row, index) => (
          <Row
            filterFields={fields}
            normalFilterFields={normalFilterFields}
            fixedColum={998}
            isSummary={true}
            dataPrefix={dataPrefix}
            isFiexedTable={isSetFixedColumnPc}
            groupCode={group.code}
            group={group}
            rowIndex={index}
            key={index}
            row={row}
            fields={group.fields}
          ></Row>
        ))}
      </InjectProvider>
    </tfoot>
  );

  return theTable;
}
